package com.maycari.captainbi.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maycari.captainbi.common.constant.CaptainBIConstant;
import com.maycari.captainbi.data.po.Captain2Po;
import com.maycari.captainbi.listener.SyncDto;
import com.maycari.captainbi.listener.SyncListener;
import com.maycari.captainbi.mapper.Captain2Dao;
import com.maycari.captainbi.service.Captain2Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maycari.tool.utils.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 商品报告及商品相关信息扩展列表 服务实现类
 * </p>
 *
 * @author 王宏伟
 * @since 2021-04-02
 */
@Service
public class Captain2ServiceImpl extends ServiceImpl<Captain2Dao, Captain2Po> implements Captain2Service {

    @Autowired
    private JmsTemplate jmsTemplate;

    @Override
    public boolean sync(Integer authorizationId, Date startTime, Date endTime) {

        SyncDto dto = new SyncDto();
        dto.setAuthorizationId(authorizationId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        dto.setBeanId("captain2ServiceImpl");
        TreeMap<String, String> params = new TreeMap<>();
        params.put("start_time", simpleDateFormat.format(startTime));
        params.put("end_time", simpleDateFormat.format(endTime));
        dto.setUrl(CaptainBIConstant.CaptainBIUrl.url_2.value());
        dto.setParams(params);
        jmsTemplate.convertAndSend(SyncListener.SYNC_LISTENER, dto);
        return true;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertBatch(JSONArray jsonArray) {
        List<Captain2Po> addList = new ArrayList<>();
        List<Captain2Po> updateList = new ArrayList<>();
        List<Captain2Po> Captain2Pos = jsonArray.toJavaList(Captain2Po.class);

        for (Captain2Po captain2Po : Captain2Pos) {
            LambdaQueryWrapper<Captain2Po> la = new LambdaQueryWrapper<>();
            la.eq(Captain2Po::getId, captain2Po.getId());
            if (count(la) == 0) {
                addList.add(captain2Po);
            } else {
                updateList.add(captain2Po);
            }
        }

        if (CollectionUtil.isNotEmpty(addList)) {
            saveBatch(addList);
        }

        if (CollectionUtil.isNotEmpty(updateList)) {
            updateBatchById(updateList);
        }
        return true;
    }
}
